<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/5/28
 * Time: 13:57
 */

namespace app\api\controller\v46;

use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\chat\LiveMessage;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveMessage;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveNoMsgRecord;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveRecord;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveReportRecord;
use app\zyhsapi\model\ZyhsConfig;
use think\Db;
use think\response\Json;

class GoodRtcLiveUser extends Auth
{
    /**
     * 发送 弹幕
     * @return Json
     */
    public function sendMsg()
    {
        $liveRecordId = input('live_record_id/d', 0);
        $content = input('content/s', '');
        if (!$liveRecordId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (empty($content))
        {
            return show(config('code.error'), '消息不能为空');
        }
        if (mb_strlen($content) > 50)
        {
            return show(config('code.error'), '消息最长50字');
        }
        $content = htmlentities($content);
        // 发送内容检测
        $res = AliyunFilterWord::checkText($content, 'article_comment');
        if ($res)
        {   // 弹幕违规 直接返回
            return show(config('code.error'), '弹幕内容违规');
        }

        $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
        $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($liveRecordId);
        if (!$recordInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $messageData = [
            'type' => 'pop_good_rtc_live_msg',
            'pop_msg' => [
                'user_info' => [
                    'uen' => $this->user['uen'],
                    'name' => $this->user['nickname'],
                ],
                'msg_info' => [
                    'id' => 0,
                    'color' => '#ffffff',
                    'content' => $content,
                ],
            ],
        ];
        // 判断是否被禁言 禁言了直接返回
        if ((new ZyhsGoodRtcLiveNoMsgRecord())->getDisenableSpeakStatus(2, $this->user['id']))
        {
            return show(424, '请求成功', $messageData);
        }
        try
        {
            $messageId = (new ZyhsGoodRtcLiveMessage())->insertGetId([
                'app_type' => 2,
                'uid' => $this->user['id'],
                'type' => 1,
                'live_record_id' => $liveRecordId,
                'mid' => $recordInfo['current_mid'],
                'content' => $content,
                'create_time' => $this->request->time(),
            ]);
            if ($messageId)
            {
                $messageData['pop_msg']['msg_info']['id'] = $messageId;
                // 发送弹幕数 自增
                $zyhsGoodRtcLiveRecordModel->where(['id' => $liveRecordId])->update(['msg_num1' => Db::raw('msg_num1 + 1')]);
                // 发送 用户弹幕
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_GOOD_RTC_LIVE_ROOM, 0, $liveRecordId), LiveMessage::MSG_TYPE_POP_GOOD_RTC_LIVE_MSG, $messageData['pop_msg']);

                return show(config('code.success'), '请求成功');
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
        return show(424, '请求成功', $messageData);
    }

    /**
     * 弹幕举报
     * @return Json
     */
    public function msgReport()
    {
        $reason = input('reason/s', '');
        $id = input('id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);

        if (empty($reason) || !$id || !$liveRecordId)
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        if (mb_strlen($reason) > 80)
        {
            return show(config('code.error'), '举报原因不能超过60字');
        }

        $reason = htmlentities($reason);

        $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
        $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($liveRecordId);
        if (!$recordInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $msgInfo = (new ZyhsGoodRtcLiveMessage())->where(['id' => $id])->find();
        if (!$msgInfo)
        {
            return show(config('code.error'), '服务异常，弹幕不存在');
        }

        if ((int)$msgInfo['live_record_id'] !== $liveRecordId)
        {
            return show(config('code.error'), '服务异常，弹幕不存在');
        }

        $reportData = [
            'app_type' => 2,
            'live_record_id' => $liveRecordId,
            'uid' => $this->user['id'],
            'uid2' => $msgInfo['uid'],
            'msg_id' => $id,
            'reason' => $reason,
            'create_time' => $this->request->time(),
        ];

        (new ZyhsGoodRtcLiveReportRecord())->insert($reportData);

        return show(config('code.success'), '举报成功');
    }

    /**
     * 用户禁言
     * @return Json
     */
    public function userDisenableSpeak()
    {
        $id = input('id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);

        if (!$id || !$liveRecordId)
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }

        $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
        $adminUserIds = $testAccountConfig['live_admin_uids'] ?? '';
        $adminUserIds = $adminUserIds ? explode(',', $adminUserIds) : [];
        if (!in_array($this->user['id'], $adminUserIds))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
        $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($liveRecordId);
        if (!$recordInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $msgInfo = (new ZyhsGoodRtcLiveMessage())->where(['id' => $id])->find();
        if (!$msgInfo)
        {
            return show(config('code.error'), '服务异常，弹幕不存在');
        }

        if ((int)$msgInfo['live_record_id'] !== $liveRecordId)
        {
            return show(config('code.error'), '服务异常，弹幕不存在');
        }

        // 判断是否被禁言
        $zyhsGoodRtcLiveNoMsgRecordModel = new ZyhsGoodRtcLiveNoMsgRecord();
        if ($zyhsGoodRtcLiveNoMsgRecordModel->getDisenableSpeakStatus(2, $this->user['id']))
        {
            return show(config('code.error'), '用户已被禁言');
        }

        $data = [
            'app_type' => 2,
            'status' => 1,
            'uid' => $msgInfo['uid'],
            'create_time' => $this->request->time(),
            'aid' => $this->user['id'],    // 禁言=>管理员uid/管理员后台aid
            'type' => 2,   // [禁言] 1=>后台管理员 2=>准有好事用户管理员
            'aid2' => 0,   // 解除禁言管理员后台aid
        ];

        $res = $zyhsGoodRtcLiveNoMsgRecordModel->SaveData($data);
        if ($res)
        {
            return show(config('code.success'), '禁言成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
